package com.thread.lianxi;

import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

public class Machine {

	public static void main(String[] args) {
		ExecutorService service = Executors.newFixedThreadPool(8); // 8个工人
		Semaphore tools = new Semaphore(5); // 5个机器；
		for (int i = 0; i < 8; i++) {
			service.execute(new Worker("工人" + i, tools));
		}
		service.shutdown();
	}

	static class Worker implements Runnable {

		private String name;
		private Semaphore tools;

		public Worker(String name, Semaphore tools) {
			this.name = name;
			this.tools = tools;
		}

		@Override
		public void run() {
			try {
				System.out.println(name + " 等待使用机器！");
				tools.acquire();// 等待使用机器
				System.out.println(name + " 获取到了机器！");
				int time = (new Random()).nextInt(5000);
				Thread.sleep(time);
				System.out.println(name + "使用机器时长" + time + "毫秒!释放机器");
				tools.release();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}

	}

}
